package club.ljwang.wechat;

import club.ljwang.entity.Result;
import club.ljwang.pojo.OrderInfo;
import club.ljwang.service.OrderService;
import cn.hutool.core.date.DateUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Auther: wangl
 * @Date: 2020/3/8 19:30
 * @Description:
 */
@RestController
@RequestMapping("pay")
public class PayController {

    @Reference
    private OrderService orderService;


    Logger log = LoggerFactory.getLogger(PayController.class);

    String serverUrl = "https://openapi.alipaydev.com/gateway.do";
    String APP_ID = "2016101700709164";
    String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCoi1cHaHxL7i/R/pILOHd2gKdk/cx8vLad0uWWai2RcmS/2tpEdBwBOeexnZKDmDiG8dl4mUerfir/gXe4IGsDLEzNF6oG16Y9X42M6AUzTBQwfD3OYxIIf9rs0EOZWb9rLbrOd5GKBv8q1P9nV4k5E4ag03NGkusY8wBvDv8u8ZZQnGtE7ZVuRfZ9nOXUKsVDhnjNQJ71uMKD0BsN3kTJwZgvPPMlFwXZdLzoX3MB8pRklPqhYuAaYdx2e8XmdSt3pz+IAvb1En312JmiaQPf0I7LNpwU4MNZeIhaldXdoWW7k4Sy3pRr3r7uiMqD3GsKQCdZeFQz/0QC2h9cTeNXAgMBAAECggEBAJDrlr5Q8idbu5SFns+1Ess7HjPx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PmX9DQo37QBOL1A0tzf8SzY7yBO/Pgp4Uvlyiv+HxTgouLSd9N/+uKlKQVuYsLOZAzp83+f0AKe5S45PJEvi3pMmTtAG58Jyud9RQOQoGqgslVojS80Mfx1/";
    String CHARSET = "UTF-8";
    String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAklBqXWMUH7kPvuxOT2oj+m7aQ/TNQTBOd6jqBzx1B86AJeX1ytGZcOkLQCtrtHFsaUi3EQmOsj/yJWRbFxeyJZeDyXVZiRGEfEqksrzB9LeiV3jATN6vsrrFNt2AfRLDK2qnoBVPOy0Ixv7qB0Ec6OXIq4x5aow+TsL1qMvOsoNWbho94NCy17XAMBzLA99kjEkwgTScvIaCaI7vDlbscj0zloKpLvAvXPl2xB+ql3xTvAut5LVOtlSMzddorggQ2BGeC6b+fWUDsarO6K0s9pdZxsKZYSxXyjaj8UelI4z2jMSWPrpTdRjPqljwoDmlate8i3uYZR0kSQBvbQSH3wIDAQAB";

    @RequestMapping("alipay")
    public void doPost(HttpServletRequest httpRequest,
                       HttpServletResponse httpResponse,
                       Integer orderId) throws ServletException, IOException {

        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2"); //获得初始化的AlipayClient
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request

        alipayRequest.setReturnUrl("http://ljwang.wicp.net/pages/orderSuccess.html?orderId=" + orderId);//支付成功之后的跳转地址
        alipayRequest.setNotifyUrl("http://ljwang.wicp.net/pay/alipayNotify.do");//在公共参数中设置回跳和通知地址(通知支付结果的地址)

        JSONObject bizJson = new JSONObject();

        String out_trade_no = outTradeNo(orderId);
        Result result = orderService.findById(orderId);
        OrderInfo orderInfo = (OrderInfo) result.getData();
        String subject = orderInfo.getSetmealName();
        orderService.updatePayNo(out_trade_no, orderId);

        bizJson.put("out_trade_no", out_trade_no);//订单号更新到数据中
        bizJson.put("total_amount", "88.88");
        bizJson.put("subject", subject);//商品名去数据库插
        bizJson.put("product_code", "QUICK_WAP_PAY");
        alipayRequest.setBizContent(bizJson.toJSONString());//填充业务参数

        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     * 生成商户订单号（年月日时分秒 + 订单号）
     *
     * @param orderId
     * @return
     */
    private String outTradeNo(Integer orderId) {
        String dateStr = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        return dateStr + orderId;
    }

    /**
     * 支付宝通知我们支付状态，在这个接口里面可以修改订单支付的状态
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/alipayNotify")
    @ResponseBody
    public String alipayNotify(HttpServletRequest request, HttpServletRequest response) throws Exception {

        log.info("支付成功, 进入异步通知接口...");

        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2"); //调用SDK验证签名
        //——请在这里编写您的程序（以下代码仅作参考）——
		/* 实际验证过程建议商户务必添加以下校验：
		1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
		2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
		3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
		4、验证app_id是否为该商户本身。
		*/
        if (signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            if (trade_status.equals("TRADE_FINISHED")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意： 尚自习的订单没有退款功能, 这个条件判断是进不来的, 所以此处不必写代码
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知

                // 修改叮当状态，改为 支付成功，已付款; 同时新增支付流水
                orderService.updatePayStatus(out_trade_no);
            }
            log.info("支付成功...");
        } else {//验证失败
            log.info("支付, 验签失败...");
        }

        return "success";
    }


}
